(*
  Copyright (c) 2009 Barry Schwartz

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*)

open XNum
open UTypes
open Substitute
open FontMetric
open Logging
open Dim
open Box
  
type font_definition = {
  fd_name : uc_string;
  fd_family : uc_string;
  fd_series : uc_string;
  fd_shape : uc_string;
  fd_min_size : num;
  fd_max_size : num;
  mutable fd_loaded_sizes : (num * font_metric) list;
  fd_data : font_load_params
}

type font = {
  f_font_def : font_definition;
  f_metric : font_metric;
  f_size : num
}

type font_table = (font_definition list) DynUCTrie.t

let empty_font_table = DynUCTrie.empty

let empty_font_definition =
  { fd_name = [| |];
    fd_family = [| |];
    fd_series = [| |];
    fd_shape = [| |];
    fd_min_size = num_zero;
    fd_max_size = num_of_int 10000;
    fd_loaded_sizes = [];
    fd_data = empty_load_params }

let empty_fonts_font =
  { f_font_def = empty_font_definition;
    f_metric = empty_font;
    f_size = num_zero }

(* table of fonts *)
let get_font_list font_table family =
  try
    DynUCTrie.find_string family font_table
  with
    | Not_found -> []
  
let add_font font_table font_def =
  let rec add_entry font_list =
    match font_list with
      | [] -> [ font_def ]
      | f :: fs ->
          if f.fd_name = font_def.fd_name &&
            f.fd_family = font_def.fd_family &&
            f.fd_series = font_def.fd_series &&
            f.fd_shape = font_def.fd_shape &&
            eq_num f.fd_min_size font_def.fd_min_size &&
            eq_num f.fd_max_size font_def.fd_max_size then
              font_list
          else
            f :: (add_entry fs)
  in
  let font_list = get_font_list font_table font_def.fd_family in
    DynUCTrie.add_string font_def.fd_family (add_entry font_list) font_table
  
let load_font fd size =
  (* |fd.fd_data.flp_size| does not contain the real size, but a scale factor. *)
  let params = { fd.fd_data with flp_size = mult_num fd.fd_data.flp_size size } in
  let font = LoadFont.load_font (UString.to_string (Array.to_list fd.fd_name)) params in
    begin
      fd.fd_loaded_sizes <-
        begin
          let rec add sizes =
            match sizes with
              | [] -> [ (size, font) ]
              | s :: ss ->
                  if lt_num (fst s) size
                  then s :: (add ss)
                  else
                    if gt_num (fst s) size then
                      (size, font) :: sizes
                    else
                      sizes
          in
            add fd.fd_loaded_sizes
        end;
      { f_font_def = fd;
        f_metric = font;
        f_size = size }
    end
  
let get_font font_table family series shape size =
  let rec choose_font fonts =
    match fonts with
      | [] -> None
      | f :: fs ->
          if f.fd_series <> series then
            choose_font fs
          else if f.fd_shape <> shape then
            choose_font fs
          else if
            le_num f.fd_min_size size &&
              (lt_num size f.fd_max_size ||
                 (eq_num f.fd_max_size num_zero ||
                    (eq_num size f.fd_max_size && eq_num f.fd_max_size f.fd_min_size))) then
                Some f
          else
            choose_font fs
  in
  let load fd size =
    try
      Some (load_font fd size)
    with
      | _ ->
          log_warn Location.empty_location "Cannot load font file `";
          log_uc_string fd.fd_name;
          log_string "'!";
          None
  in
    match choose_font (get_font_list font_table family) with
      | None -> None
      | Some fd ->
          let rec iter sizes =
            begin
              match sizes with
                | [] -> load fd size
                | (s, f) :: ss ->
                    if lt_num s size then
                      iter ss
                    else if eq_num s size then
                      Some { f_font_def = fd;
                             f_metric = f;
                             f_size = size; }
                    else
                      load fd size
            end
          in
            iter fd.fd_loaded_sizes
  
let declare_font font_table name family series shape size params =
  add_font font_table
    { fd_name = name;
      fd_family = family;
      fd_series = series;
      fd_shape = shape;
      fd_min_size = fst size;
      fd_max_size = snd size;
      fd_loaded_sizes = [];
      fd_data = params }

let initialise_font_table () =
  let font_table =
    ref (declare_font DynUCTrie.empty [|  |] [|  |] [|  |] [|  |]
           (num_zero, (num_of_int 10000)) empty_load_params)
  in
    !font_table
